﻿/*-----------------------------------------------------------------------------------------------
// Copyright (C) 2016 华跃博弈科技有限公司 
//
// 文件名：         BaseEntity.cs
// 文件功能描述：   领域实体对象基类，所有领域实体对象都必须继承该类
//
// 
// 创建标识：       庞永飞  2016-04-18
//
// 修改标识：
// 修改描述：
//
// 备注：	
// 				
//-----------------------------------------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HYBY.Task.DataEntity {
 
  [Serializable]
  public class BaseEntity {

    /// <summary>
    /// 实体对象唯一编码
    /// </summary>
    public long ID { get; set; }

    public override bool Equals(object obj) {
      return Equals(obj as BaseEntity);
    }

    public virtual bool Equals(BaseEntity other) {
      if (other == null)
        return false;

      if (ReferenceEquals(this, other))
        return true;

      if (!IsTransient(this) &&
          !IsTransient(other) &&
          Equals(ID, other.ID)) {
        var otherType = other.GetUnproxiedType();
        var thisType = GetUnproxiedType();
        return thisType.IsAssignableFrom(otherType) ||
                otherType.IsAssignableFrom(thisType);
      }

      return false;
    }

    public override int GetHashCode() {
      if (Equals(ID, default(int)))
        return base.GetHashCode();
      return ID.GetHashCode();
    }

    public static bool operator ==(BaseEntity x, BaseEntity y) {
      return Equals(x, y);
    }

    public static bool operator !=(BaseEntity x, BaseEntity y) {
      return !(x == y);
    }

    private static bool IsTransient(BaseEntity obj) {
      return obj != null && Equals(obj.ID, default(int));
    }

    private Type GetUnproxiedType() {
      return GetType();
    }
  }
}
